import React, {useContext} from "react";
import {Text, TouchableHighlight, View} from "react-native";
import styles from "./index.style";
import {MoreOptionsDrawerItemProps} from "@/types/common";
import MaterialCommunityIcons from "@expo/vector-icons/MaterialCommunityIcons";
import * as DocumentPicker from "expo-document-picker";
import * as ImagePicker from "expo-image-picker";
import {CameraType} from "expo-image-picker";
import {ResponseCode} from "@/types/api-common";
import {useTheme} from "@/contexts/ThemeContext";
import {useSafeAreaInsets} from "react-native-safe-area-context";
import {ChatDetailContext} from "@/components/Chat/ChatDetail";
import {useChatSessionActions} from "@/hooks/chat/chat-session";
import {useChatMessageActions} from "@/hooks/chat/chat-message";
import {useStompSend} from "@/hooks/stomp/stomp-send";
import {useUserProfileState} from "@/hooks/user/user-profile";
import {SessionType} from "@/types/chat-session";
import {ChatMessage, MessageStatus, MessageType} from "@/types/chat-message";
import {getSnowflakeId} from "@/utils/snow-flake-utils";
import {
    cacheFile,
    generateVideoThumbnail,
    getFileMD5,
    getFileSimpleDescription,
    getFileType,
    updateFileCacheServerUrl
} from "@/utils/file-utils";
import {File, FileType} from "@/types/file-upload";
import {uploadFileApi} from "@/services/api/file-upload";
import SystemUtils from "@/utils/system-utils";
import AlertServices from "@/components/Global/Alert/service";

const MAX_FILE_SIZE = 100 * 1024 * 1024; // 100MB


interface MoreOptionsDrawerProps {
    onUploadSuccess?: () => void;
}


export default function MoreOptionsDrawer({
                                              onUploadSuccess,
                                          }: MoreOptionsDrawerProps) {
    const {colors} = useTheme();
    const insets = useSafeAreaInsets();
    const {sessionId, sessionType, flatListRef} = useContext(ChatDetailContext)
    const {addMessage} = useChatMessageActions();
    const {currentUser} = useUserProfileState();
    const {updateSession} = useChatSessionActions();
    const {sendChatMessage} = useStompSend();

    const sendMediaMessage = async (file: File) : Promise<ChatMessage<any, any>> => {
        const fileType = getFileType(file);
        const fileUrl = await cacheFile(file);
        const message: ChatMessage<any, any> = {
            revokeStatus: false,
            system: false,
            messageId: getSnowflakeId(),
            sessionId,
            messageType: fileType as MessageType,
            content: {
                url: fileUrl
            },
            user: {
                id: currentUser.id,
                avatar: currentUser.avatar,
                name: currentUser.nickname,
                updateTime: currentUser.updateTime,
            },
            status: sessionType === SessionType.SINGLE && sessionId === currentUser.id ?
                MessageStatus.SENT : // 自己发送给自己的消息状态为SENT
                MessageStatus.SENDING, // 发送给其他人的消息状态为SENDING
            createTime: new Date().getTime()
        };
        if (fileType === FileType.VIDEO) {
            // 如果为视频，则生成缩略图]
            const {uri} = await generateVideoThumbnail(message.messageId,fileUrl);
            message.content.thumbnail = uri;
        }
        await addMessage(message);
        await updateSession({
            lastMessageId: message.messageId,
            lastMessage: getFileSimpleDescription(file.fileName, fileType),
            sessionId,
        });
        return message;
    }


    async function uploadFilesToServer(results: ImagePicker.ImagePickerResult) {
        let totalFileSize = 0;
        results.assets?.forEach((item) => {
            totalFileSize += item.fileSize || 0;
        });
        const files: File[] = [];
        if (results.assets) {
            for (const item of results.assets) {
                const md5 = await getFileMD5(item.uri);
                files.push({
                    uri: item.uri,
                    fileName: item.fileName || `file_${item.uri.split("/").pop()}`,
                    type: item.mimeType || "application/octet-stream",
                    md5,
                    size: item.fileSize || 0,
                });
            }
        }

        if (files && files.length > 0) {
            if (totalFileSize > MAX_FILE_SIZE) {
                AlertServices.showAlert('error',"媒体文件总大小超过100MB");
                return;
            }
            const uploadPromises = files.map(async (file) => {
                const msg = await sendMediaMessage(file); // 发送消息
                const formData = new FormData();
                const uri = file.uri;
                const fileName = file.fileName;
                const fileType = file.type;
                formData.append("file", {
                    uri,
                    name: fileName,
                    type: fileType,
                } as any);

                return uploadFileApi(formData)
                    .then((response) => {
                        if (response.data.code === ResponseCode.SUCCESS) {
                            onUploadSuccess && onUploadSuccess();
                            // 发送ws消息
                            if (sessionType === SessionType.GROUP || (sessionType === SessionType.SINGLE && sessionId !== currentUser.id)) {
                                sendChatMessage({...msg, sessionType , content: {...msg.content, url: response.data.data.fileUrl}});
                            }
                            // 更新消息缓存
                            updateFileCacheServerUrl(file.md5, response.data.data.fileUrl)
                        } else {
                            alert("上传失败");
                            console.error(response.data.message);
                        }
                    })
                    .catch((error) => {
                        console.error("上传失败:", error);
                        SystemUtils.showSystemAlert("上传失败，请稍后重试");
                    });
            });
            // 移动到最新消息
            flatListRef.current?.scrollToEnd({animated: true});
            await Promise.all(uploadPromises); // 并行上传文件
        }
    }

    const options: MoreOptionsDrawerItemProps[] = [
        {
            label: "相册",
            icon: "image",
            onPress: async () => {
                let results = await ImagePicker.launchImageLibraryAsync({
                    mediaTypes: ['images','videos','livePhotos'],
                    allowsMultipleSelection: true,
                    selectionLimit: 5,
                    quality: 1,
                    videoMaxDuration: 30,
                });
                if (results.assets?.some(asset => (asset.fileSize || 0) > MAX_FILE_SIZE)) {
                    AlertServices.showAlert('error', "单个媒体文件大小超过100MB");
                    return;
                }
                if (results.assets && results.assets.length > 0) {
                    await uploadFilesToServer(results);
                }
            },
        },
        {
            label: "相机",
            icon: "camera",
            onPress: async () => {
                let results = await ImagePicker.launchCameraAsync({
                    mediaTypes: ImagePicker.MediaTypeOptions.All,
                    quality: 1,
                    selectionLimit: 5,
                    videoMaxDuration: 30,
                    cameraType: CameraType.back,
                });
                if (results.assets && results.assets.length > 0) {
                    await uploadFilesToServer(results);
                }
            },
        },
        {
            label: "文件",
            icon: "folder",
            onPress: async () => {
                const selectedResult = await DocumentPicker.getDocumentAsync({
                    type: "*/*",
                    multiple: true,
                });
                console.log(selectedResult.assets);
            },
        },
        {
            label: "语音通话",
            icon: "phone",
            onPress: () => {
                // 语音通话逻辑
                alert("语音通话功能尚未实现");
            }
        },
        {
            label: "视频通话",
            icon: "video",
            onPress: () => {
                // 视频通话逻辑
                alert("视频通话功能尚未实现");
            }
        },
    ];

    return (
        <View style={[styles.drawer, {backgroundColor: colors.background, paddingBottom: insets.bottom}]}>
            {options.map((option, index) => (
                <View style={styles.drawerButton} key={index}>
                    <TouchableHighlight
                        underlayColor={colors.backgroundHighlight}
                        style={{borderRadius: 8}}
                        onPress={() => {
                            option.onPress?.();
                        }}
                    >
                        <View
                            style={[
                                styles.iconContainer,
                                {backgroundColor: colors.inputBackground},
                            ]}
                        >
                            {option.icon && (
                                <MaterialCommunityIcons
                                    style={styles.icon}
                                    name={option.icon as any}
                                    size={24}
                                    color={colors.text.secondary}
                                />
                            )}
                        </View>
                    </TouchableHighlight>
                    <Text
                        style={[styles.drawerButtonText, {color: colors.text.secondary}]}
                    >
                        {option.label}
                    </Text>
                </View>
            ))}
        </View>
    );
}
